<?php if (!defined('FIT_PATH')) exit('No direct script access allowed');
/**
 * @copyright 2009 - 2011 Bincent.com. All Rights Reserved.
 * @license http://www.apache.org/licenses/LICENSE-2.0
 * @package FitPHP
 * @subpackage helper
 * 
 * @author Hongbin Hsu <hongbin.hsu@gmail.com> Initial.
 * @version $Id: helper/url.php 1.0 2009-07-18 13:34 hongbin.hsu $
 */

// ------------------------------------------------------------------------
/**
 * 头文件重定向
 *
 * @param string $uri	URL地址
 * @param string $method: location or redirect
 * @param int $http_response_code
 * @return	void
 */
if (!function_exists('redirect'))
{
	function redirect($url = '', $method = 'location', $http_response_code = 302)
	{
		switch(strtolower($method)){
			case 'refresh': 
				header('Refresh:0;url=' . $url);
				break;
			default:
				header("Location: ".$url, true, $http_response_code);
				break;
		}
		exit;
	}
}

//----------------------------------------------------------
/**
 * 远程提交数据
 *
 * @param string $path
 * @param string $query
 * @param string $method
 * @return string
 */
if (!function_exists('visit'))
{
	function visit($path, $query, $method = 'post')
	{
		/*获取主机地址*/
		$array = explode('/', $path);
		if (strtolower($array[0]) != "http:") { return false; }
		$host = $array[2];
		
		$method = strtoupper($method);
		
		/*构造页面访问请求*/
		$post = "{$method} {$path} HTTP:/1.1\r\n";
		$post.= "Host: {$host}\r\n";
		$post.= "Content-type: application/x-www-form-urlencoded\r\n";
		$post.= "User-Agent: Mozilla 4.0\r\n";
		$post.= "Content-length: ".strlen($query)."\r\n";
		$post.= "Connection: close\r\n\r\n";
		$post.= "{$query}";
		
		/*使用fsockopen连接页面并将请求信息提交*/
		$port = explode(':', $host);
		$port = empty($port[1]) ? 80 : intval($port[1]);
		$fp = fsockopen($host, $port);
		fwrite($fp, $post);
		do {
			$row = fgets($fp);
			$content.= $row;
		}while ($row);
		/*关闭服务器链接并返回页面的全部数据*/
		fclose($fp);
		
		return $content;
	}
}

//----------------------------------------------------------
/**
 * 生成短链接
 *
 * @param string $url
 * @return string
 */
if (!function_exists('short_url'))
{
	function short_url($url){
		$url = crc32($url);
		$result = sprintf("%u", $url);

		while($result > 0) {
			$s = $result % 62;
			if ($s > 35) {
				$s = chr($s + 61);            
			} elseif ($s > 9 && $s <=35) {
				$s = chr($s + 55);
			}
			$shorturl .= $s;
			$result = floor($result / 62);
		}

		return $shorturl;    
	}
}